package com.xuetang.controller.admin;

import com.xuetang.common.ApiResponse;
import com.xuetang.entity.AdminUser;
import com.xuetang.security.JwtTokenUtil;
import com.xuetang.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员登录控制器
 */
@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/admin")
public class AdminLoginController {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 默认路径，返回API状态
     */
    @GetMapping({ "/", "/login" })
    public ApiResponse index() {
        return ApiResponse.success("血糖小程序后台管理API服务");
    }

    /**
     * 处理登录请求 - JSON提交
     */
    @PostMapping("/login")
    public ApiResponse login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");

        try {
            AdminUser adminUser = adminUserService.login(username, password);

            if (adminUser != null) {
                // 生成JWT token
                String token = jwtTokenUtil.generateToken(username);

                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("user", adminUser);

                return ApiResponse.success(data);
            } else {
                return ApiResponse.error(401, "用户名或密码错误");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/user/info")
    public ApiResponse getUserInfo(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        // 简单实现，实际项目中应该从token中解析用户信息
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            try {
                // 从token中获取用户名
                String username = jwtTokenUtil.getUsernameFromToken(token);
                if (username != null) {
                    AdminUser adminUser = adminUserService.findByUsername(username);
                    if (adminUser != null) {
                        Map<String, Object> data = new HashMap<>();
                        data.put("id", adminUser.getId());
                        data.put("username", adminUser.getUsername());
                        data.put("name", adminUser.getRealName());
                        data.put("avatar", adminUser.getAvatar());
                        data.put("roles", new String[] { "admin" });

                        return ApiResponse.success(data);
                    }
                }
            } catch (Exception e) {
                return ApiResponse.error(500, "获取用户信息失败：" + e.getMessage());
            }
        }

        return ApiResponse.error(401, "未授权");
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ApiResponse logout() {
        return ApiResponse.success("退出成功");
    }
}